<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="168px">
      <el-form-item label="单据号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入单据号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="scId">
        <el-select v-model="queryParams.scId" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in ck" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option label="待审核" value="0" ></el-option>
          <el-option label="审核通过" value="3" ></el-option>
          <el-option label="审核拒绝" value="6" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作人" prop="createBy">
        <el-select v-model="queryParams.createBy" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间" >
        <el-date-picker clearable
                        v-model="queryParams.createMinTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
        至
        <el-date-picker clearable
                        v-model="queryParams.createMaxTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核人" prop="approveBy">
        <el-select v-model="queryParams.approveBy" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.name"
                     :value="item.name" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核时间" >
        <el-date-picker clearable
                        v-model="queryParams.approveMinTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
        至
        <el-date-picker clearable
                        v-model="queryParams.approveMaxTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:StockAdjustSheet:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:StockAdjustSheet:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="StockAdjustSheetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据号" align="center" prop="code" width="170" show-overflow-tooltip/>
      <el-table-column label="仓库名称" align="left" prop="scName" />
      <el-table-column label="业务类型" align="center" prop="bizType" >
        <template slot-scope="scope">
          <span>{{ scope.row.bizType == 0 ? "入库" : "出库" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调整原因" align="center" prop="reasonId" width="100">
        <template slot-scope="scope">
          <span>{{ getReasonName(scope.row.reasonId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作时间" align="left" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="left" prop="createBy" width="100"/>
      <el-table-column label="状态" align="left" prop="status" >
        <template slot-scope="scope">
          <span>{{ scope.row.status == 0 ? "待审核" : scope.row.status == 3 ? "审核成功" : "审核拒绝"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="approveBy" width="100"/>
      <el-table-column label="审核时间" align="center" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="description" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="selectOrder(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
            v-if="scope.row.status != 3"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="statusUpdate(scope.row)"
            v-if="scope.row.status != 3"
          >审批</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
            v-if="scope.row.status != 3"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存数量调整单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
        <div style="display: inline-block;width: 300px;"><p>仓库：{{ this.form.scName }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>业务类型：{{ this.form.bizType == 0 ? "入库" : "出库" }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>调整原因：{{ getReasonName(this.form.reasonId) }}</p></div>
        <br>
        <div style="display: inline-block;width: 700px;">
          <p>
            备注： <textarea cols="70" rows="3" style="border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid" v-model="description" :disabled="title !== '审批'"/>
          </p>
        </div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>状态：<span :style="{color: statusColor}">{{ this.form.status==0 ? '待审核' : (this.form.status==3 ? '审核通过' : '审核拒绝') }}</span></p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.form.status == 6"><p>拒绝原因：{{ this.form.refuseReason }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>操作人：{{ this.form.createBy }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>操作时间：{{ parseTime(this.form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;" v-if="this.form.approveBy"><p>审核人：{{ this.form.approveBy }}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.form.approveTime"><p>审核时间：{{ this.form.approveTime }}</p></div>
        <br>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px">
        <el-table v-loading="loading" :data="tblStockNumAdjustSheetDetailList" @selection-change="handleSelectionChange" >
          <el-table-column label="商品编号" prop="baseDataProduct.code" align="center" />
          <el-table-column label="商品名称" prop="baseDataProduct.name" align="center" width="150"/>
          <el-table-column label="商品sku编号" prop="baseDataProduct.skuCode" align="center" width="100"/>
          <el-table-column label="商品外部编号" prop="baseDataProduct.externalCode" align="center" width="100"/>
          <el-table-column label="单位" prop="baseDataProduct.unit" align="center" />
          <el-table-column label="规格" prop="baseDataProduct.spec" align="center" />
          <el-table-column label="商品类目" prop="baseDataProduct.baseDataProductCategory.name" align="center" />
          <el-table-column label="商品品牌" prop="baseDataProduct.baseDataProductBrand.name" align="center" />
          <el-table-column label="调整库存数量" prop="stockNum" align="center" width="100"/>
          <el-table-column label="备注" prop="description" align="center" />
        </el-table>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
        <h3 style="margin:0 0 15px 10px;font-weight: bolder;">合计</h3>
        <div style="display: inline-block;margin-left:50px">
          调价品种数：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled v-model="this.form.productNum">
        </div>
        <div style="display: inline-block;margin-left:50px">
          库存调整数量：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled v-model="this.form.diffNum">
        </div>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="success" @click="submitForm(3)" v-if="this.title == '审批'">审批通过</el-button>
        <el-button type="danger" @click="submitForm(6)" v-if="this.title == '审批'&&this.form.status!=6">审批拒绝</el-button>
        <el-button @click="cancel" v-if="this.title != '查看'">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 拒绝原因 -->
    <el-dialog :title="title" :visible.sync="refuseOpen" width="500px" append-to-body>
      <el-form ref="refuseForm" :model="refuseForm" :rules="refuseRules" label-width="80px">
        <el-form-item label="拒绝原因" prop="reason">
          <el-input type="textarea" v-model="refuseForm.reason" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="refuseSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStockAdjustSheet, getStockAdjustSheet, delStockAdjustSheet, addStockAdjustSheet, updateStockAdjustSheet } from "@/api/system/StockAdjustSheet";
import {parseTime} from "../../../utils/ruoyi";
import { addLog } from "@/api/system/log";
import { updateStock,listStock } from "@/api/system/stock";
import { center, user } from "@/api/system/order";
import { listReason } from "@/api/system/reason";

export default {
  name: "StockAdjustSheet",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTblStockNumAdjustSheetDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存数量调整单表格数据
      StockAdjustSheetList: [],
      // 库存数量调整单明细表格数据
      tblStockNumAdjustSheetDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //拒绝原因弹窗
      refuseOpen:false,
      //弹窗状态颜色
      statusColor:"rgb(100, 100, 100)",
      //备注
      description: null,
      //调整原因
      reasonList: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        scId: null,
        status: null,
        createBy: null,
        createTime: null,
        approveBy: null,
        approveTime: null,
      },
      // 表单参数
      form: {},
      // 仓库下拉框
      ck: [],
      // 用户(审核人、操作人、销售员)下拉框
      user: [],
      // 表单校验
      rules: {
        code: [
          { required: true, message: "单据号不能为空", trigger: "blur" }
        ],
        scId: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
        productNum: [
          { required: true, message: "调价品种数不能为空", trigger: "blur" }
        ],
        diffNum: [
          { required: true, message: "库存调整数量不能为空", trigger: "blur" }
        ],
        reasonId: [
          { required: true, message: "调整原因不能为空", trigger: "blur" }
        ],
        bizType: [
          { required: true, message: "业务类型不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        createById: [
          { required: true, message: "创建人ID不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateBy: [
          { required: true, message: "修改人不能为空", trigger: "blur" }
        ],
        updateById: [
          { required: true, message: "修改人ID不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "修改时间不能为空", trigger: "blur" }
        ],
      },
      //拒绝原因
      refuseForm: {
        reason: ''
      },
      refuseRules: {
        reason: [
          { required: true, message: "拒绝原因不能为空", trigger: "blur" }
        ]
      },
      //商品库存记录的id列表
      stockLogList:[],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    parseTime,
    /** 查询库存数量调整单列表 */
    getList() {
      this.loading = true;
      center(this.ck).then(response => {
        this.ck = response.rows;
        console.log(this.ck);
      });
      user(this.user).then(response => {
        this.user = response.rows;
        console.log(this.user);
      });
      listReason().then(response => {
        this.reasonList = new Map();
        for (let i = 0; i < response.rows.length; i++) {
          this.reasonList.set(response.rows[i].id, response.rows[i].name)
        }
        console.log(this.reasonList);
      });
      listStockAdjustSheet(this.queryParams).then(response => {
        this.StockAdjustSheetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getReasonName(id) {
      return this.reasonList.get(id) || '未知原因';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        scId: null,
        productNum: null,
        diffNum: null,
        reasonId: null,
        bizType: null,
        status: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        approveBy: null,
        approveTime: null,
        refuseReason: null
      };
      this.tblStockNumAdjustSheetDetailList = [];
      this.resetForm("form");
    },
    //审批按钮
    statusUpdate(row){
      this.reset();

      const id = row.id || this.ids
      getStockAdjustSheet(id).then(response => {
        this.form = response.data;
        this.tblStockNumAdjustSheetDetailList = response.data.tblStockNumAdjustSheetDetailList;
        this.description = this.form.description;
        this.open = true;
        this.title = "审批";
      });

      if (row.status==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.status==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else {
        this.statusColor = "rgb(255, 0, 0)";
      }
    },
    //拒绝原因
    refuseSubmit() {
      this.$refs["refuseForm"].validate(valid => {
        if (valid) {
          this.form.status=6;
          this.form.approveBy='系统管理员';
          this.form.refuseReason=this.refuseForm.reason
          this.form.approveTime=new Date();
          updateStockAdjustSheet(this.form).then(response => {
            this.$modal.msgError("审批拒绝");
            this.refuseOpen = false;
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.$router.push({
        path: '/num/add',
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      this.$router.push({
        path:'/num/update',
        query:{
          id: id,
        }
      })
    },
    // 查看按钮
    selectOrder(row) {
      if (row.status == 0) {
        this.statusColor = "rgb(100, 100, 100)";
      } else if (row.status == 3) {
        this.statusColor = "rgb(82, 196, 26)";
      } else {
        this.statusColor = "rgb(255, 0, 0)";
      }

      getStockAdjustSheet(row.id).then(response => {
        this.form = response.data;
        this.tblStockNumAdjustSheetDetailList = response.data.tblStockNumAdjustSheetDetailList;
        this.description = this.form.description;
        this.open = true;
        this.title = "查看";
        console.log(this.tblStockNumAdjustSheetDetailList)
      });
    },
    /** 审核通过、审核拒绝按钮 */
    submitForm(status) {
      if (status==6){
        this.open = false;
        this.refuseOpen=true
      }else {
        this.form.status=status;
        this.form.approveBy='系统管理员';
        this.form.approveTime=new Date();
        this.form.description = this.description;
        console.log(this.form);
        updateStockAdjustSheet(this.form).then(response => {
          if(status==3){
            //审核通过后添加商品库存记录
            for (let i = 0; i < this.form.tblStockNumAdjustSheetDetailList.length; i++) {
              let stockNum = 0;
              if (this.form.bizType == 0){
                stockNum = this.form.tblStockNumAdjustSheetDetailList[i].oriStockNum + this.form.tblStockNumAdjustSheetDetailList[i].stockNum;
              }else{
                stockNum = this.form.tblStockNumAdjustSheetDetailList[i].oriStockNum - this.form.tblStockNumAdjustSheetDetailList[i].stockNum;
              }
              if (stockNum < 0){
                this.$modal.msgError("第"+(i+1)+"行商品库存不足,不能出库");
                return;
              }
              let taxAmount = stockNum * this.form.tblStockNumAdjustSheetDetailList[i].price - this.form.tblStockNumAdjustSheetDetailList[i].oriStockNum * this.form.tblStockNumAdjustSheetDetailList[i].price;
              let stockLog = {
                id: generateUniqueId(this.stockLogList),
                scId: this.form.scId,
                productId: this.form.tblStockNumAdjustSheetDetailList[i].productId,
                oriTaxPrice: this.form.tblStockNumAdjustSheetDetailList[i].price,
                curTaxPrice: this.form.tblStockNumAdjustSheetDetailList[i].price,
                oriStockNum: this.form.tblStockNumAdjustSheetDetailList[i].oriStockNum,
                curStockNum: stockNum,
                stockNum: stockNum - this.form.tblStockNumAdjustSheetDetailList[i].oriStockNum,
                taxAmount: taxAmount,
                createBy: '系统管理员',
                createById: '1',
                createTime: new Date(),
                bizType: 10,
                bizId: this.form.id,
                bizCode: this.form.code,
                bizDetailId: this.form.tblStockNumAdjustSheetDetailList[i].id,
              }
              addLog(stockLog).then(response => {})
              // 根据仓库id和商品id修改商品库存中的库存数量和总金额
              listStock({scId: this.form.scId, productId: this.form.tblStockNumAdjustSheetDetailList[i].productId}).then(response => {
                let stockNum = 0;
                if (this.form.bizType === 0){
                  stockNum = this.form.tblStockNumAdjustSheetDetailList[i].stockNum + response.rows[0].stockNum;
                }else{
                  stockNum = response.rows[0].stockNum - this.form.tblStockNumAdjustSheetDetailList[i].stockNum;
                }
                let stock = {
                  id: response.rows[0].id,
                  scId: response.rows[0].scId,
                  productId: response.rows[0].productId,
                  stockNum: stockNum,
                  taxPrice: response.rows[0].taxPrice,
                  taxAmount: response.rows[0].taxPrice * stockNum,
                }
                updateStock(stock).then(response => {})
              })
            }
            this.$modal.msgSuccess("审批成功");
          }else {
            this.$modal.msgError("审批拒绝")
          }
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除库存数量调整单编号为"' + ids + '"的数据项？').then(function() {
        return delStockAdjustSheet(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 库存数量调整单明细序号 */
    rowTblStockNumAdjustSheetDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 库存数量调整单明细添加按钮操作 */
    handleAddTblStockNumAdjustSheetDetail() {
      let obj = {};
      obj.productId = "";
      obj.oriStockNum = "";
      obj.stockNum = "";
      obj.description = "";
      obj.orderNo = "";
      this.tblStockNumAdjustSheetDetailList.push(obj);
    },
    /** 库存数量调整单明细删除按钮操作 */
    handleDeleteTblStockNumAdjustSheetDetail() {
      if (this.checkedTblStockNumAdjustSheetDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的库存数量调整单明细数据");
      } else {
        const tblStockNumAdjustSheetDetailList = this.tblStockNumAdjustSheetDetailList;
        const checkedTblStockNumAdjustSheetDetail = this.checkedTblStockNumAdjustSheetDetail;
        this.tblStockNumAdjustSheetDetailList = tblStockNumAdjustSheetDetailList.filter(function(item) {
          return checkedTblStockNumAdjustSheetDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleTblStockNumAdjustSheetDetailSelectionChange(selection) {
      this.checkedTblStockNumAdjustSheetDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/StockAdjustSheet/export', {
        ...this.queryParams
      }, `StockAdjustSheet_${new Date().getTime()}.xlsx`)
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 重新获取数据
      vm.getList();
    });
  }
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}
</script>
